<?php

class AppController extends Controller
{
    public $components = array('MainMenu', 'Auth');
    public $helpers = array('ehtml', 'Html', 'Form', 'FilterBlock', 'EditForm', 'Calendar');
    public $uses = array();
    public $noCache = true;

    function beforeFilter()
    {
        Auth_sessionBegin();

		global $request_time, $pre_filter_time, $prepare_time;
		$pre_filter_time = microtime(true);
		$prepare_time = $pre_filter_time-$request_time;

        Page::initObj($this);
        Auth::SetController($this);

        if (Auth::o()->is('admin')) {
            Configure::write('Config.language', 'ru');
        }
    }

    function msgError($msg, $error_code = null)
    {
        $adds = isset($error_code) ? " (".__d(null, "error_code", true)." ".sprintf(__d(null, "number_with_sign", true), $error_code).")" : "";
        $this->Session->setFlash($msg.$adds, 'default', array('msg-type' => 'error'));
    }

    function msgNotice($msg, $notice = null)
    {
        $adds = isset($notice) ? " ({$notice})" : "";
        $this->Session->setFlash($msg.$adds, 'default', array('msg-type' => 'notice'));
    }

    function msgWarning($msg, $notice = null)
    {
        $adds = isset($notice) ? " ({$notice})" : "";
        $this->Session->setFlash($msg.$adds, 'default', array('msg-type' => 'warning'));
    }

    function beforeRender()
    {
        if (!empty($this->pageTitle)) {
            $this->pageTitle = (strlen(PAGE_TITLE_PREFIX) ? PAGE_TITLE_PREFIX . ' :: ' : '').$this->pageTitle;
        }
        $this->MainMenu->inite();
        Layout::o()->widget['menu'] =& $this->MainMenu;
        //$this->set('main_menu', $this->MainMenu->getMainItems());
        $this->set('left_menu', $this->MainMenu->getLeftMenu());
        //$this->set('breadcrumbs', $this->MainMenu->getBreadcrumbs());
        $this->set('Page', Page::objForView());

		global $pre_render_time, $filter_time, $pre_filter_time;
        $pre_render_time = microtime(true);
        $filter_time = $pre_render_time - $pre_filter_time;

        header("Accept-Ranges: none");
        if ($this->noCache) {
            header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
            header("Pragma: no-cache");
            header("Expires: 0");
        }

        if (Auth::o()->is('client_admin')) {
            $id = Auth::o()->realId();

            $ClientAdmin = new ClientAdmin();
            $ClientAdmin->rel("Client");
            $result = $ClientAdmin->read(null, $id);
            $result["Client"]["frozen_balance"] = $ClientAdmin->Client->getReservedBalance($result["Client"]["id"])->value;
            $this->set('client_data', $result);
        }
    }

    function _error($code = 404)
    {
        $this->layout = 'default';
		$this->passedArgs[0] = $code;
		$this->passedArgs[1] = "is_inner";
		$this->setAction('error');
    }

    function error()
    {
        if (Auth::o()->is('guest') && !(isset($this->passedArgs[1]) && ($this->passedArgs[1] == "is_inner"))) {
            $this->redirect('/login', null, true);
            exit();
        }

        $this->access = '*';
		$codes = array(
			100 => "Continue",
			101 => "Switching Protocols",
			200 => "OK",
			201 => "Created",
			202 => "Accepted",
			203 => "Non-Authoritative Information",
			204 => "No Content",
			205 => "Reset Content",
			206 => "Partial Content",
			300 => "Multiple Choices",
			301 => "Moved Permanently",
			302 => "Found",
			303 => "See Other",
			304 => "Not Modified",
			305 => "Use Proxy",
			307 => "Temporary Redirect",
			400 => "Bad Request",
			401 => "Unauthorized",
			402 => "Payment Required",
			403 => "Forbidden",
			404 => "Not Found",
			405 => "Method Not Allowed",
			406 => "Not Acceptable",
			407 => "Proxy Authentication Required",
			408 => "Request Time-out",
			409 => "Conflict",
			410 => "Gone",
			411 => "Length Required",
			412 => "Precondition Failed",
			413 => "Request Entity Too Large",
			414 => "Request-URI Too Large",
			415 => "Unsupported Media Type",
			416 => "Requested range not satisfiable",
			417 => "Expectation Failed",
			500 => "Internal Server Error",
			501 => "Not Implemented",
			502 => "Bad Gateway",
			503 => "Service Unavailable",
			504 => "Gateway Time-out"
		);

		$code = isset($this->passedArgs[0]) ? $this->passedArgs[0] : 0;

		if (! isset($codes[$code])) {
		    $code = 404;
		}
	    $this->layout = 'error';
	    $this->pageTitle = ($code == 404) ? __d('http', 'http_error_404', true) : $code . ' ' .$codes[$code];
		$this->viewPath = 'errors';
		$this->set('name', $code . ' ' .$codes[$code]);
		$this->set('message', '');
		header('HTTP/1.1 '.$code);
        $this->render('error');

	    try {
            set_response($code);
	    } catch (Exception $e) {}

        exit();
    }

    /**
     * Вывод последовательности октетов клиенту.
     *
     * @param string $stream
     */
    function renderOctets($stream)
    {
        nodebug();
        $this->data = $stream;
        if (! headers_sent()) {
    		header("Content-Length: ".strlen($this->data));
        }
        $this->render(null, "empty", VIEWS."layouts/out_octets.ctp");
    }

    /**
     * Вывод содержимого указанного файла клиенту.
     *
     * @param string $file_path
     */
    function renderFile($file_path, $params = array())
    {
        nodebug();
        $type = "application/octet-stream";
        $name = null;
        $attach = false;
        if (! empty($params["type"]) && is_string($params["type"])) {
            $type = $params["type"];
        }
        if (! empty($params["name"]) && is_string($params["name"])) {
            $name = $params["name"];
        }
        if (! empty($params["attach"])) {
            $attach = true;
        }
        $content_name = isset($name) ? "; name=\"{$name}\"": "";
        $disposition_name = isset($name) ? "; filename=\"{$name}\"": "";
        $disposition = $attach ? "attachment" : "inline";
        header("Content-Type: {$type}{$content_name}");
        header("Content-Disposition: {$disposition}{$disposition_name}");

        $this->data = $file_path;
        if (! headers_sent() && file_exists($this->data) && is_readable($this->data)) {
    		header("Content-Length: ".filesize($this->data));
        }
        $this->render(null, "empty", VIEWS."layouts/out_file.ctp");
    }
}

?>